package com.ikingtech.platform.service.system.user.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.role.api.RoleUserApi;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.user.entity.UserRoleDO;
import com.ikingtech.platform.service.system.user.service.repository.UserRoleRepository;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class RoleUserService implements RoleUserApi {

    private final UserRoleRepository userRoleRepo;

    @Override
    public void removeUserRole(String roleId) {
        this.userRoleRepo.remove(Wrappers.<UserRoleDO>query().lambda().eq(UserRoleDO::getRoleId, roleId).eq(UserRoleDO::getTenantCode, Me.tenantCode()));
    }

    @Override
    public void bindUserRole(String roleId, List<String> userIds) {
        this.userRoleRepo.saveBatch(Tools.Coll.convertList(userIds, userId -> {
            UserRoleDO entity = new UserRoleDO();
            entity.setId(Tools.Id.uuid());
            entity.setUserId(userId);
            entity.setRoleId(roleId);
            entity.setDomainCode(Me.domainCode());
            entity.setTenantCode(Me.tenantCode());
            entity.setAppCode(Me.appCode());
            return entity;
        }));
    }

    @Override
    public void unbindUserRole(String roleId, List<String> userIds) {
        this.userRoleRepo.remove(Wrappers.<UserRoleDO>lambdaQuery()
                .eq(UserRoleDO::getRoleId, roleId)
                .in(UserRoleDO::getUserId, userIds));
    }
}
